import React,{useState} from 'react'
import { Search, Toast } from 'react-vant'
import {useNavigate} from 'react-router-dom'
import axios from 'axios'
export default function Searchs() {
  const navigate = useNavigate()
  let [value, setValue] = useState('')
  let [list,setlist]=useState([])
  let find=async(e)=>{
    let {data}=await axios.get('http://localhost:3000/findlist',{params:{name:e}})
    console.log(data);
    if(data.data.length>0){
      localStorage.setItem('list',JSON.stringify(value))
      setlist(data.data)
    }
    
    
  }

  return (
    <div>
      <Search
        value={value}
        onChange={(e)=>setValue(e)} 
        placeholder="请输入搜索关键词"
        showAction
        onSearch={(e)=>find(e)}
        onCancel={() => {
          navigate('/')
          setValue('');
        }}
        onClear={()=>{setValue(''),setlist([])}}
      />
      <div>
        <button onClick={()=>{setValue(localStorage.getItem('list')), find(JSON.parse(localStorage.getItem('list')).toString())}}>{localStorage.getItem('list')?JSON.parse(localStorage.getItem('list')).toString():'搜索历史'}</button>
        
      </div>
      <div style={{display:'flex',flexWrap:'wrap'}}>
        {
          list.map(item=>{
            return <div key={item._id} style={{width:'150px',margin:'10px',textAlign:'center'}}>
              <img src={item.img} style={{width:'100px',height:'100px'}} alt="" />
              <p>{item.title}</p>
            </div>
          })
        }
      </div>
    </div>
  )
}
